﻿using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.EvidenceDerivation;
using LdtJudge.DataEngine.Model.OptimizationModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using LdtJudge.DataEngine.Model.XMLConfigModel.OptimzeMode;
using LdtJudge.DataEngine.Model.XMLConfigModel.SameNodeConfigModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace LdtDataEngin.ModuleDetail.BaseModule.MultiFack
{
    /// <summary>
    /// 内容合并
    /// </summary>
    public class MultiFactUnion : MultiFactBase
    {

        /// <summary>
        /// 通用方法处理
        /// 该方法为应用
        /// </summary>
        /// <param name="templateNode">模板节点</param>
        /// <param name="personxml">人员数据</param>
        /// <param name="xmlConfigModels">配置节点数据</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        /// <returns></returns>
        public override string MultiFactHandleCommon(XmlNode templateNode, Dictionary<Tuple<string, string>, XmlNode> personxml, List<SameNodeXml> xmlConfigModels, SameNodeHandleType nodeHandleType)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 数据同节点合并
        /// </summary>
        /// <param name="templateNode">模板节点</param>
        /// <param name="neednode">需要遍历的节点</param>
        /// <param name="xmlConfigModels">节点配置</param>
        /// <param name="resultnode">返回结果内容</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        public void MultiFactUnionNode(XmlNode templateNode, XmlNode neednode, List<SameNodeXml> xmlConfigModels, XmlNode resultnode, SameNodeHandleType nodeHandleType, bool IdReset = false)
        {
            #region 针对事实要素节点属性内容特殊处理
            if (templateNode.Name == "事实要素")
            {
                string xmlpath = base.GetXmlPath(templateNode);
                XmlNode elementnode = neednode.SelectSingleNode(xmlpath);
                foreach (XmlAttribute attr in elementnode.Attributes)
                {
                    XmlAttribute attributetemp = (XmlAttribute)resultnode.OwnerDocument.ImportNode(attr, true);
                    resultnode.Attributes.Append(attributetemp);
                }
            }
            #endregion

            foreach (XmlNode nodemplate in templateNode.ChildNodes)
            {
                string xmlpath = base.GetXmlPath(nodemplate);
                string rootpath = xmlpath;
                if (templateNode.Name != "事实要素")
                {
                    rootpath = xmlpath.Substring(xmlpath.LastIndexOf('/') + 1);
                }
                List<XmlNode> nobase = neednode.SelectNodes(rootpath).Cast<XmlNode>().ToList();
                if (nobase.Count > 1)
                {
                    XmlDocument xmldoc;
                    if (neednode.OwnerDocument == null)
                    {
                        xmldoc = new XmlDocument();
                        xmldoc.LoadXml(string.Format("<{0}></{0}>", templateNode.ParentNode.Name));
                    }
                    else
                    {
                        xmldoc = neednode.OwnerDocument;
                    }
                    XmlNode node_one = xmldoc.CreateElement(templateNode.Name);
                    XmlNode node_onechild = node_one.OwnerDocument.ImportNode(nobase[0], true);
                    node_one.AppendChild(node_onechild);
                    for (int i = 0; i < nobase.Count; i++)
                    {
                        XmlNode xmlNodeFacttConfirm = resultnode.OwnerDocument.CreateElement(templateNode.Name);
                        XmlNode node_two = xmldoc.CreateElement(templateNode.Name);
                        XmlNode node_twochild = node_two.OwnerDocument.ImportNode(nobase[i], true);
                        node_two.AppendChild(node_twochild);
                        if (neednode.OwnerDocument == null)
                        {
                            //表示当前节点为事实要素节点的第一级子节点
                            XmlDocument xmldoctempone = (XmlDocument)xmldoc.Clone();
                            XmlDocument xmldoctemptwo = (XmlDocument)xmldoc.Clone();
                            XmlNode node_onet = xmldoctempone.ImportNode(node_one, true);
                            XmlNode node_twot = xmldoctemptwo.ImportNode(node_two, true);
                            xmldoctempone.FirstChild.AppendChild(node_onet);
                            xmldoctemptwo.FirstChild.AppendChild(node_twot);
                            this.MultiFactUnionXml(templateNode, xmldoctempone, xmldoctemptwo, xmlConfigModels, xmlNodeFacttConfirm, nodeHandleType, IdReset);
                        }
                        else
                        {//表示当前节点的父节点不是事实要素
                            this.MultiFactUnionXml(templateNode, node_one, node_two, xmlConfigModels, xmlNodeFacttConfirm, nodeHandleType, IdReset);
                        }
                        node_one = xmlNodeFacttConfirm.Clone();
                    }

                    foreach (XmlNode childnode in node_one.ChildNodes)
                    {
                        XmlNode xmlnodetemp = resultnode.OwnerDocument.ImportNode(childnode, true);
                        resultnode.AppendChild(xmlnodetemp);
                    }

                }
                else if (nobase.Count == 1)
                {//如果当前节点的数据只有一个，则进行递归处理下级
                    XmlNode childenode = resultnode.OwnerDocument.ImportNode(nobase[0], false);
                    resultnode.AppendChild(childenode);
                    this.MultiFactUnionNode(nodemplate, nobase[0], xmlConfigModels, childenode, nodeHandleType,IdReset);
                }
            }

        }

        /// <summary>
        /// 将分人员数据进行合并
        /// </summary>
        /// <param name="templateNode">模板开始节点</param>
        /// <param name="personxml">分人员集合数据</param>
        /// <param name="xmlConfigModels">合并配置</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        public Dictionary<Tuple<string, string>, XmlNode> MultiFactUnionPersonXml(XmlNode templateNode, Dictionary<Tuple<string, string>, List<XmlNode>> personxml, List<SameNodeXml> xmlConfigModels, SameNodeHandleType nodeHandleType)
        {
            Dictionary<Tuple<string, string>, XmlNode> dicPersonxml = new Dictionary<Tuple<string, string>, XmlNode>();
            foreach (var person in personxml)
            {
                //新建一个此案由的根节点xml
                XmlDocument result = new XmlDocument();
                string reultxml = string.Format("<{0}></{0}>", templateNode.ParentNode.Name);
                result.LoadXml(reultxml);
                XmlNode xmlNodeFact = result.CreateElement("事实要素");
                result.DocumentElement.AppendChild(xmlNodeFact);
                XmlNode node1 = person.Value[0];
                if (person.Value.Count > 1)
                {
                    for (int i = 1; i < person.Value.Count; i++)
                    {
                        XmlNode node2 = person.Value[i];
                        xmlNodeFact.RemoveAll();
                        this.MultiFactUnionXml(templateNode, node1, node2, xmlConfigModels, xmlNodeFact, nodeHandleType);
                        node1 = result.Clone();
                    }
                    dicPersonxml.Add(person.Key, result);
                }
                else
                {
                    dicPersonxml.Add(person.Key, node1);
                }
            }
            return dicPersonxml;
        }
        
        /// <summary>
        /// 将认定数据和待认定数据进行合并
        /// </summary>
        /// <param name="templateNode">模板开始节点</param>
        /// <param name="personxml">分人员待认定数据</param>
        /// <param name="Confirmnode">认定要素内容</param>
        /// <param name="xmlConfigModels">合并配置</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        public XmlNode MultiFactUnionPersonXml(XmlNode templateNode, Dictionary<Tuple<string, string>, XmlNode> personxml, XmlDocument Confirmnode, List<SameNodeXml> xmlConfigModels, SameNodeHandleType nodeHandleType)
        {
            string reultxml = string.Format("<{0}></{0}>", templateNode.ParentNode.Name);
            XmlDocument node1 = null;
            if (Confirmnode != null && Confirmnode.DocumentElement != null && Confirmnode.SelectSingleNode("//事实要素") != null)
            {
                node1 = Confirmnode;
            }
            else
            {
                XmlDocument no1t = new XmlDocument();
                no1t.LoadXml(reultxml);
                XmlNode xmlNodeFact = no1t.CreateElement("事实要素");
                no1t.DocumentElement.AppendChild(xmlNodeFact);
                node1 = no1t;
            }
            foreach (var person in personxml)
            {
                XmlNode node2 = person.Value;
                //新建一个此案由的根节点xml
                XmlDocument result = new XmlDocument();
                result.LoadXml(reultxml);
                XmlNode xmlNodeFact = result.CreateElement("事实要素");
                result.DocumentElement.AppendChild(xmlNodeFact);
                this.MultiFactUnionXml(templateNode, node1, node2, xmlConfigModels, xmlNodeFact, nodeHandleType);
                //将当前结果为下一次循环赋值
                node1 = result;
            }

            //base.InsertAllNodeIndex(node1);
            dataContext.InteractiveShow.LogShow("\r\n----------★最终[事实要素类型 4 ]的合并为：★----------\r\n" + node1.OuterXml);
            return node1;
        }
        
        /// <summary>
        /// 将认定数据和待认定数据进行合并
        /// </summary>
        /// <param name="templateNode">模板开始节点</param>
        /// <param name="mainperxml">分人员主要待认定数据</param>
        /// <param name="deputyperxml">分人员副待认定数据</param>
        /// <param name="xmlConfigModels">合并配置</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        public Dictionary<Tuple<string, string>, XmlNode> MultiFactUnionPersonXml(XmlNode templateNode, Dictionary<Tuple<string, string>, XmlNode> mainperxml, Dictionary<Tuple<string, string>, XmlNode> deputyperxml, List<SameNodeXml> xmlConfigModels, SameNodeHandleType nodeHandleType)
        {
            Dictionary<Tuple<string, string>, XmlNode> keyValues = new Dictionary<Tuple<string, string>, XmlNode>();
            string reultxml = string.Format("<{0}></{0}>", templateNode.ParentNode.Name);
            foreach (var mperxml in mainperxml)
            {
                XmlNode node1 = mperxml.Value;
                //新建一个此案由的根节点xml
                XmlDocument result = new XmlDocument();
                result.LoadXml(reultxml);
                XmlNode xmlNodeFact = result.CreateElement("事实要素");
                result.DocumentElement.AppendChild(xmlNodeFact);
                if (deputyperxml.ContainsKey(mperxml.Key))
                {
                    this.MultiFactUnionXml(templateNode, node1, deputyperxml[mperxml.Key], xmlConfigModels, xmlNodeFact, nodeHandleType);
                    keyValues.Add(mperxml.Key, result); 
                }
                else
                {
                    keyValues.Add(mperxml.Key, node1);
                }
            }
            return keyValues;
        }
        
        /// <summary>
        /// 进行节点数据合并
        /// </summary>
        /// <param name="templateNode">模板节点</param>
        /// <param name="no1">主xml</param>
        /// <param name="no2">从xml，将当前的xml合并到主xml中</param>
        /// <param name="xmlConfigModels">合并配置</param>
        /// <param name="resultxml">返回结果内容</param>
        /// <param name="nodeHandleType">同节点判定类型</param>
        public void MultiFactUnionXml(XmlNode templateNode, XmlNode no1, XmlNode no2, List<SameNodeXml> xmlConfigModels, XmlNode resultxml, SameNodeHandleType nodeHandleType,bool IdReset=false)
        {
            #region 针对事实要素的属性进行特殊处理
            if (templateNode.Name == "事实要素")
            {//抽取同案要素
                foreach (XmlAttribute xmlattr in templateNode.Attributes)
                {
                    string xmlpath = base.GetXmlPath(templateNode);
                    XmlNode node1 = no1.SelectSingleNode(xmlpath + "/@" + xmlattr.Name);
                    XmlNode node2 = no2.SelectSingleNode(xmlpath + "/@" + xmlattr.Name);
                    XmlNode Nodemerge = node2 == null ? node1 : node2;
                    if (Nodemerge != null)
                    {
                        //XmlAttribute notemp = (XmlAttribute)resultxml.OwnerDocument.ImportNode(Nodemerge, true);
                        //resultxml.Attributes.Append(notemp);
                    }
                }
            }
            #endregion
            foreach (XmlNode nodemplate in templateNode.ChildNodes)
            {
                string xmlpath = base.GetXmlPath(nodemplate);
                //默认将当前节点路径赋值节点查询路径
                string rootpath = xmlpath;
                if (templateNode.Name != "事实要素")
                {
                    rootpath = xmlpath.Substring(xmlpath.LastIndexOf('/') + 1);
                }
                List<XmlNode> nobase = no1.SelectNodes(rootpath).Cast<XmlNode>().ToList();
                List<XmlNode> nodetwo = no2.SelectNodes(rootpath).Cast<XmlNode>().ToList();
                SameNodeXml xmlConfigModel = xmlConfigModels.FirstOrDefault(con => con.XmlPath == xmlpath);
                if (nobase.Count == 0 || nodetwo.Count == 0)
                {

                    if (nodetwo.Count == 0 && nobase.Count > 0)
                    {
                        //如果被对比的节点不存在当前遍历的节点，则将主xml进行导入到返回结果中。
                        foreach (XmlNode nob in nobase)
                        {
                            XmlNode nodetemp = resultxml.OwnerDocument.ImportNode(nob, true);
                            resultxml.AppendChild(nodetemp);
                        }
                    }
                    else if (nobase.Count == 0 && nodetwo.Count > 0)
                    {
                       
                        XmlNode nodde2temp = no2.Clone();
                        XmlNode nodechild = nodde2temp;
                        if (nodde2temp.OwnerDocument == null)
                        {//表示当前节点是根节点
                            nodde2temp.FirstChild.FirstChild.RemoveAll();
                            nodechild = nodde2temp.FirstChild.FirstChild;
                        }
                        else
                        {//表示当前节点不是根节点，也就是事实要素
                            nodde2temp.RemoveAll();
                        }
                        foreach (XmlNode nodetempt in nodetwo)
                        {
                            XmlNode node2t = nodechild.OwnerDocument.ImportNode(nodetempt, true);
                            nodechild.AppendChild(node2t);
                        }
                        this.MultiFactUnionNode(templateNode, nodde2temp, xmlConfigModels, resultxml, nodeHandleType,IdReset);
                    }
                }
                else
                {
                    if (nobase != null && nobase.Count > 0 && nodetwo != null && nodetwo.Count > 0)
                    {  //判定存在当前节点信息 
                        for (int i = 0; i < nobase.Count;)
                        {
                            bool nobaseisadd = true;
                            XmlNode no_one = nobase[i];
                            for (int j = 0; j < nodetwo.Count;)
                            {
                                bool nodetwoisadd = true;
                                XmlNode no_two = nodetwo[j];
                                bool IssameNode = base.IsSameNode(xmlConfigModel, no_one, no_two, nodeHandleType);
                                if (IssameNode)
                                {
                                    //如果节点相同
                                    XmlNode newnod = null;
                                    if (xmlConfigModel != null && xmlConfigModel.OverAll == "1")
                                    {
                                        string id = no_two.Attributes["id"].Value;
                                        //当前节点为整体处理方式
                                        newnod = resultxml.OwnerDocument.ImportNode(no_one, false);
                                        newnod.Attributes["id"].Value = Snowflake.Instance().GetId().ToString();
                                        
                                        if (IdReset)
                                        {
                                            newnod.Attributes["id"].Value = id;
                                        }
                                        var initialnodeid = no_two.Attributes["initialnodeid"]?.Value;
                                        if (!string.IsNullOrWhiteSpace(initialnodeid))
                                        {
                                            if (newnod.Attributes["initialnodeid"] == null)
                                            {
                                                XmlAttribute initialnodeidAttr = newnod.OwnerDocument.CreateAttribute("initialnodeid");
                                                initialnodeidAttr.Value = initialnodeid;
                                                newnod.Attributes.Append(initialnodeidAttr);
                                            }
                                            else
                                            {
                                                newnod.Attributes["initialnodeid"].Value = initialnodeid;
                                            }

                                        }
                                    }
                                    else
                                    {
                                        //属性集合
                                        newnod = resultxml.OwnerDocument.CreateElement(no_one.Name);
                                        List<XmlAttribute> listAttr = new List<XmlAttribute>();
                                        listAttr.AddRange(no_one.Attributes.Cast<XmlAttribute>().Where(x => x.Name != "initialnodeid").ToList());
                                        listAttr.AddRange(no_two.Attributes.Cast<XmlAttribute>().Where(x => x.Name != "initialnodeid").ToList());
                                        List<string> initialnodeids = new List<string>();
                                        var oneInitId = no_one.Attributes["initialnodeid"]?.Value;
                                        var twoInitId = no_two.Attributes["initialnodeid"]?.Value;
                                        if (!string.IsNullOrWhiteSpace(oneInitId))
                                        {
                                            var oneidList = oneInitId.Split(";").ToList();
                                            foreach (var item in oneidList)
                                            {
                                                if (!initialnodeids.Contains(item))
                                                {
                                                    initialnodeids.Add(item);
                                                }
                                            }
                                        }
                                        if (!string.IsNullOrWhiteSpace(twoInitId))
                                        {
                                            var twoidList = twoInitId.Split(";").ToList();
                                            foreach (var item in twoidList)
                                            {
                                                if (!initialnodeids.Contains(item))
                                                {
                                                    initialnodeids.Add(item);
                                                }
                                            }
                                        }
                                        foreach (XmlAttribute attr in listAttr)
                                        {
                                            if (!newnod.Attributes.Cast<XmlAttribute>().ToList().Any(at => at.Name == attr.Name))
                                            {
                                                //如果不存在当前的属性，则进行添加
                                                XmlAttribute attributet = (XmlAttribute)newnod.OwnerDocument.ImportNode(attr, true);
                                                newnod.Attributes.Append(attributet);
                                            }
                                        }
                                        if (initialnodeids != null && initialnodeids.Any())
                                        {
                                            XmlAttribute attrInitId = (XmlAttribute)newnod.OwnerDocument.CreateAttribute("initialnodeid");
                                            attrInitId.Value = string.Join(";", initialnodeids);
                                            newnod.Attributes.Append(attrInitId);
                                        }
                                        if (newnod.Attributes["id"] != null)
                                        {
                                            if (IdReset)
                                            {
                                                if (no_one.Attributes["id"] != null && no_two.Attributes["id"] != null)
                                                {
                                                    newnod.Attributes["id"].Value = no_one.Attributes["id"].Value + "," + no_two.Attributes["id"].Value + "," + Snowflake.Instance().GetId().ToString();
                                                }
                                                else if (no_one.Attributes["id"] != null)
                                                {
                                                    newnod.Attributes["id"].Value = no_one.Attributes["id"].Value + "," + Snowflake.Instance().GetId().ToString();
                                                }
                                                else if (no_two.Attributes["id"] != null)
                                                {
                                                    newnod.Attributes["id"].Value = no_two.Attributes["id"].Value + "," + Snowflake.Instance().GetId().ToString();
                                                }
                                            }
                                            else
                                            {
                                                newnod.Attributes["id"].Value = Snowflake.Instance().GetId().ToString();
                                            }
                                        }
                                    }
                                    resultxml.AppendChild(newnod);
                                    //进行递归获取子节点信息
                                    MultiFactUnionXml(nodemplate, no_one, no_two, xmlConfigModels, newnod, nodeHandleType,IdReset);
                                    //如果是相同节点，则将遍历的集合中进行移除
                                    nobase.Remove(no_one);
                                    nodetwo.Remove(no_two);
                                    nobaseisadd = false;
                                    nodetwoisadd = false;
                                    break;
                                   
                                }
                                if (nodetwoisadd)
                                    j++;
                            }
                            if (nobaseisadd)
                                i++;
                        }
                        //将没有对比上的节点进行导入
                        foreach (XmlNode node in nobase)
                        {//如果确定不是同一个节点，则进行导入当前节点
                            XmlNode nodetemp = resultxml.OwnerDocument.ImportNode(node, true);
                            resultxml.AppendChild(nodetemp);
                        }
                        foreach (XmlNode node in nodetwo)
                        {//如果确定不是同一个节点，则进行导入当前节点
                            XmlNode nodetemp = resultxml.OwnerDocument.ImportNode(node, true);
                            resultxml.AppendChild(nodetemp);
                        }

                    }
                }
            }
        }

        /// <summary>
        /// 将所有的要素信息合并成一个节点
        /// </summary>
        /// <param name="rootname">案由名称</param>
        /// <param name="SuitPersonxmlNode">诉请集合</param>
        /// <param name="confirmdocument">确认要素</param>
        /// <param name="DifferentListNode">有异议要素</param>
        /// <param name="FinalUnMerge">最终待认定</param>
        /// <param name="mernode">最终合并</param>
        /// <param name="docGenerateUsageXml">文书生成使用要素</param>
        /// <returns></returns>
        public XmlDocument MultFactAllMerge(string rootname, Dictionary<Tuple<string, string>, XmlNode> SuitPersonxmlNode, Dictionary<Tuple<string, string>, XmlNode> ResultxmlNode, XmlDocument confirmdocument, Dictionary<Tuple<string, string>, XmlNode> DifferentListNode, Dictionary<Tuple<string, string>, XmlNode> FinalUnMerge, XmlNode mernode, XmlNode docGenerateUsage, CaseCauseModel caseCauseModel)
        {
            //TODO:ZSW 证据与事实要素关系建立
            List<FactElementNodeCorredRecord> resultMergeRecords = new List<FactElementNodeCorredRecord>();
            string xmlmerge = string.Empty;
            foreach (var suitper in SuitPersonxmlNode)
            {
                XmlNode node = suitper.Value.SelectSingleNode("//诉请要素");
                string suit = base.SetXmlFlag("", suitper.Key.Item2, suitper.Key.Item1, "诉请要素", node.OuterXml);
                xmlmerge += suit;
            }
            foreach (var suitper in ResultxmlNode)
            {
                XmlNode node = suitper.Value.SelectSingleNode("//结果要素");
                string suit = base.SetXmlFlag("", suitper.Key.Item2, suitper.Key.Item1, "结果要素", node.OuterXml);
                xmlmerge += suit;
            }
            string confirmxmlstr = base.SetXmlFlag("1", "", "", "事实要素", confirmdocument.SelectSingleNode("//事实要素").OuterXml);
            string difffactxmlstr = string.Empty;
            foreach (var diffenxml in DifferentListNode)
            {
                XmlNode node = diffenxml.Value.SelectSingleNode("//事实要素");
                string diff = base.SetXmlFlag("3", diffenxml.Key.Item2, diffenxml.Key.Item1, "事实要素", node.OuterXml);
                difffactxmlstr += diff;
            }
            string unconfirmxmlstr = string.Empty;
            foreach (var unconfirmxml in FinalUnMerge)
            {
                XmlNode node = unconfirmxml.Value.SelectSingleNode("//事实要素");
                if (node != null)
                {
                    XmlDocument xmlDocumentRh = new XmlDocument();
                    var nodeContent = DeleteSourceNodeIdAttr(node.OuterXml);
                    xmlDocumentRh.LoadXml(nodeContent);
                    XmlNode xmlNodeRy = xmlDocumentRh.SelectSingleNode("//主张方");
                    if (xmlNodeRy != null)
                    {
                        if (xmlNodeRy.Attributes["主张方姓名或名称"] == null)
                        {
                            XmlAttribute facttype = xmlDocumentRh.CreateAttribute("主张方姓名或名称");
                            facttype.Value = unconfirmxml.Key.Item2;
                            xmlNodeRy.Attributes.Append(facttype);
                        }
                        if (xmlNodeRy.Attributes["主张方诉讼地位"] == null)
                        {
                            XmlAttribute facttype = xmlDocumentRh.CreateAttribute("主张方诉讼地位");
                            facttype.Value = unconfirmxml.Key.Item1;
                            xmlNodeRy.Attributes.Append(facttype);
                        }
                    }
                    string uncon = base.SetXmlFlag("2", unconfirmxml.Key.Item2, unconfirmxml.Key.Item1, "事实要素", xmlDocumentRh.OuterXml);
                    unconfirmxmlstr += uncon;
                }
            }
            XmlDocument Fact4xml = new XmlDocument();
            Fact4xml.LoadXml(mernode.SelectSingleNode("//事实要素").OuterXml);
            DataSoursModel dataSoursModel = new DataSoursModel();
            XmlUtilCommon xmlUtilCommon = new XmlUtilCommon() { dataContext = dataContext };
            dataSoursModel = xmlUtilCommon.GetXMLByDataModel(Fact4xml);
            XmlDocument xmlDocumentt = new XmlDocument();
            List<FactElementNodeCorredRecord> finalMergeRecords = new List<FactElementNodeCorredRecord>();
            xmlUtilCommon.DataModelIDByResetAndRecord(dataSoursModel.dataModelList, "", "","4",null,out finalMergeRecords);
            xmlDocumentt = xmlUtilCommon.DataModelByXml(dataSoursModel.dataModelList, "");
            string finalmergexml = base.SetXmlFlag("4", "", "", "事实要素", xmlDocumentt.OuterXml);
            //TODO:ZSW 证据与事实要素关系建立
            if (finalMergeRecords != null && finalMergeRecords.Any())
                resultMergeRecords = finalMergeRecords;
            //文书生成要素
            string docGenerateUsageXml = "";
            if(docGenerateUsage!=null)
            {
                XmlDocument Fact8xml = new XmlDocument();
                Fact8xml.LoadXml(docGenerateUsage.OuterXml);
                DataSoursModel fact8DataSoursModel = new DataSoursModel();
                fact8DataSoursModel = xmlUtilCommon.GetXMLByDataModel(Fact8xml);
                XmlDocument Fact8xmlNew = new XmlDocument();
                List<FactElementNodeCorredRecord> docGenerateRecords = new List<FactElementNodeCorredRecord>();
                xmlUtilCommon.DataModelIDByResetAndRecord(fact8DataSoursModel.dataModelList, "", "", "8", null, out docGenerateRecords);
                Fact8xmlNew = xmlUtilCommon.DataModelByXml(fact8DataSoursModel.dataModelList, "");
                docGenerateUsageXml = base.SetXmlFlag("8", "", "", "事实要素", Fact8xmlNew.OuterXml);
                //TODO:ZSW 证据与事实要素关系建立
                if (docGenerateRecords != null && docGenerateRecords.Any())
                    resultMergeRecords = docGenerateRecords;
            }
            #region TODO:ZSW 证据与事实要素关系建立
            //调整证据与合并后要素关系的事实要素ID
            if (dataContext.DataLayerOpt.EvidenceFactRelations != null
                    && dataContext.DataLayerOpt.EvidenceFactRelations.Any(x => x.ElementType == "2"))
            {
                if (resultMergeRecords != null && resultMergeRecords.Any())
                {
                    foreach (var item in dataContext.DataLayerOpt.EvidenceFactRelations.Where(x => x.ElementType == "2"))
                    {
                        var mergeRecord = resultMergeRecords.FirstOrDefault(x => x.MergeBeforeId == item.FactElenemtId);
                        if (mergeRecord != null)
                        {
                            item.FactElenemtId = mergeRecord.MergeAfterId;
                        }
                    }
                }
            }
            #endregion
            string mergexml = xmlmerge + confirmxmlstr + difffactxmlstr + unconfirmxmlstr + finalmergexml + docGenerateUsageXml;
            var extractCause = dataContext.DataCommon.ExtractCaseCausesList.FirstOrDefault(x => x.AllParentId.Contains(caseCauseModel.CC_ID));
            mergexml = string.Format("<{0} 案由名称=\"{1}\" 案由ID=\"{2}\">" + mergexml + "</{0}>", rootname, extractCause.CC_Name, extractCause.CC_ID);
            XmlDocument document = new XmlDocument();
            document.LoadXml(mergexml);
            //将合并后的内容全部加入序号
            //base.InsertAllNodeIndex(document);
           
            document = XmlUtility.EscapeNodeIndexAndBlank(document);
            document = XmlUtility.EscpeNodeBlankPer(document);
            base.InsertAllNodeIndexNew(document, "");
            return document;

        }

        /// <summary>
        /// 事实要素比对记录数据组装
        /// </summary>
        public void AssemblaCorredRecords(List<FactElementNodeCorredRecord> oneRecords, List<FactElementNodeCorredRecord> twoRecords,int type)
        {
            if(oneRecords!=null && oneRecords.Any() && twoRecords!=null && twoRecords.Any())
            {
                foreach (var oneitem in oneRecords)
                {
                    FactElementNodeCorredRecord twoData = new FactElementNodeCorredRecord();
                    twoData = twoRecords.FirstOrDefault(x => x.MergeBeforeId == oneitem.MergeBeforeId);
                    if (twoData != null)
                    {
                        if (type == 1)
                        {
                            oneitem.MergeBeforeId = oneitem.MergeAfterId;
                            oneitem.MergeAfterId = twoData.MergeAfterId;
                            oneitem.ElementType = twoData.ElementType;
                        }
                        else if (type == 2)
                        {
                            var oneOldAfterId = oneitem.MergeAfterId;
                            var beforeNewId = twoData.MergeAfterId;
                            oneitem.MergeBeforeId = beforeNewId;
                            var resultData = twoRecords.FirstOrDefault(x => x.MergeBeforeId == oneOldAfterId);
                            if (resultData != null)
                            {
                                oneitem.MergeAfterId = resultData.MergeAfterId;
                            }
                        }

                    }
                }
            }
        }


        //TODO:ZSW 证据与事实要素关系建立
        /// <summary>
        /// 添加节点对应的原始节点属性
        /// </summary>
        public string LoadSourceNodeIdAttr(string xmlContent, List<EvidenceFactRelationModel> relModels)
        {
            XDocument xDocument = XDocument.Parse(xmlContent);
            var xElementList = xDocument.Elements();
            if (xElementList != null && xElementList.Any())
            {
                foreach (var item in xElementList)
                {
                    AddSourceNodeIdAttr(item, relModels);
                }
            }
            var content = xDocument.ToString();
            return content;
        }

        //TODO:ZSW 证据与事实要素关系建立
        /// <summary>
        /// 添加节点初始属性
        /// </summary>
        /// <param name="xElement"></param>
        private void AddSourceNodeIdAttr(XElement xElement, List<EvidenceFactRelationModel> relModels)
        {
            var idAttr = xElement.Attribute("id");
            if (idAttr != null)
            {
                var relModel = relModels.Where(x => x.FactElenemtId == idAttr.Value).ToList();
                if (relModel != null)
                {
                    var sourNodeIds = relModel.Where(x => !string.IsNullOrWhiteSpace(x.EvidenceElementId)).Select(x => x.EvidenceElementId).ToList();
                    string sourNodeId = string.Join(";", sourNodeIds);
                    if (!string.IsNullOrWhiteSpace(sourNodeId))
                    {
                        var nodeIdAttr = xElement.Attribute("initialnodeid");
                        if (nodeIdAttr == null)
                            xElement.SetAttributeValue("initialnodeid", sourNodeId);
                        else
                            nodeIdAttr.Value = sourNodeId;
                    }
                }
            }
            var childs = xElement.Elements();
            if (childs != null && childs.Any())
            {
                foreach (XElement child in childs)
                {
                    AddSourceNodeIdAttr(child, relModels);
                }
            }
        }

        /// <summary>
        /// 删除节点中initialnodeid属性
        /// </summary>
        public string DeleteSourceNodeIdAttr(string xmlContent)
        {
            string resultContent = xmlContent;
            if (!string.IsNullOrWhiteSpace(xmlContent))
            {
                XDocument handleDoc = XDocument.Parse(xmlContent);
                var handleNodes = handleDoc.Descendants().Where(x => x.Attribute("initialnodeid") != null && !string.IsNullOrWhiteSpace(x.Attribute("initialnodeid").Value));
                if (handleNodes != null && handleNodes.Any())
                {
                    foreach (XElement nodeItem in handleNodes)
                    {
                        nodeItem.Attribute("initialnodeid").Remove();
                    }
                }
                resultContent = handleDoc.ToString();
            }
            return resultContent;
        }
    }
}
